package com.frejoys.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.frejoys.common.dto.ad.AdPageDto;
import com.frejoys.common.dto.admin.AdAddDto;
import com.frejoys.common.dto.admin.AdUpDto;
import com.frejoys.common.dto.admin.DelIdDto;
import com.frejoys.common.enums.EAdType;
import com.frejoys.common.enums.EFileSize;
import com.frejoys.common.enums.EStatus;
import com.frejoys.common.util.AppConfigUtil;
import com.frejoys.common.util.CommonUtil;
import com.frejoys.common.util.TimeUtil;
import com.frejoys.common.vo.ad.AdPageVo;
import com.frejoys.common.vo.ad.UserAdVo;
import com.frejoys.dao.entity.Ad;
import com.frejoys.dao.entity.Store;
import com.frejoys.dao.mapper.AdMapper;
import com.frejoys.dao.mapper.StoreMapper;
import com.frejoys.service.AdService;
import com.frejoys.service.ResourceLibraryService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

// 广告
@Service
@RequiredArgsConstructor
public class AdServiceImpl extends ServiceImpl<AdMapper, Ad> implements AdService {

    private final StoreMapper storeMapper;

    @Override
    public Ad getInfo(Integer id) {
        return baseMapper.selectById(id);
    }

    @Override
    public boolean addInfo(AdAddDto dto) {
        return save(new Ad() {{
            setCommonId(dto.getCommonId());
            setType(dto.getType());
            setCover(dto.getCover());
            setUrl(dto.getUrl());
            setStartTime(TimeUtil.unixTime(dto.getStartTime()));
            setEndTime(TimeUtil.unixTime(dto.getEndTime()));
            setType(dto.getType());
        }});
    }

    @Override
    public boolean upInfo(AdUpDto dto) {

        LambdaUpdateWrapper<Ad> wrapper = new UpdateWrapper().lambda();
        wrapper.eq(Ad::getId, dto.getId());

        if (StrUtil.isNotEmpty(dto.getCover())) {
            wrapper.set(Ad::getCover, dto.getCover());
        }
        if (StrUtil.isNotEmpty(dto.getUrl())) {
            wrapper.set(Ad::getUrl, dto.getUrl());
        }
        if (dto.getType() != null) {
            wrapper.set(Ad::getType, dto.getType());
        }
        if (dto.getCommonId() != null) {
            wrapper.set(Ad::getCommonId, dto.getCommonId());
        }
        if (dto.getStartTime() != null && dto.getEndTime() != null) {
            wrapper.set(Ad::getStartTime, TimeUtil.unixTime(dto.getStartTime()));
            wrapper.set(Ad::getEndTime, TimeUtil.unixTime(dto.getEndTime()));
        }

        return update(wrapper);
    }

    @Override
    public boolean delInfo(DelIdDto dto) {
        LambdaUpdateWrapper<Ad> adUpdateWrapper = new LambdaUpdateWrapper<>();
        adUpdateWrapper.set(Ad::getStatus, dto.getStatus());
        adUpdateWrapper.eq(Ad::getId, dto.getId());
        return update(adUpdateWrapper);
    }

    /**
     * 后台查询广告
     *
     * @param dto
     */
    @Override
    public IPage<AdPageVo> pageListAd(AdPageDto dto) {
        Page<Ad> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<Ad> wrapper = Wrappers.lambdaQuery();
        if (dto.getSite() != null) {
            wrapper.eq(Ad::getSite, dto.getSite());
        }
        if (dto.getType() != null) {
            wrapper.eq(Ad::getType, dto.getType());
        }
        if (StrUtil.isNotEmpty(dto.getStartTime())) {
            wrapper.ge(Ad::getStartTime, TimeUtil.unixTime(dto.getStartTime()));
        }
        if (StrUtil.isNotEmpty(dto.getEndTime())) {
            wrapper.le(Ad::getEndTime, TimeUtil.unixTime(dto.getEndTime()));
        }
        Page<Ad> adPage = baseMapper.selectPage(page, wrapper);
        IPage<AdPageVo> adPageVoIPage = adPage.convert(ad -> BeanUtil.copyProperties(ad, AdPageVo.class));
        List<AdPageVo> adList = adPageVoIPage.getRecords();
        if (CollectionUtil.isNotEmpty(adList)) {

            List<Integer> ids = adList.stream().map(AdPageVo::getCommonId).filter(Objects::nonNull).toList();

            Map<Integer, Store> storeMap = new HashMap<>();

            //查出店铺信息
            if (!ids.isEmpty()){
                List<Store> stores = storeMapper.getStoreNameList(ids);
                storeMap = stores.stream().collect(Collectors.toMap(Store::getId, store -> store));
            }

            for (AdPageVo a : adList) {
                a.setCoverUrl(AppConfigUtil.getUrlPrefix(a.getCover()));
                a.setUrl(AppConfigUtil.getUrlPrefix(a.getUrl()));

                if (a.getType() == EAdType.storeAd.getValue()){

                    if (storeMap.containsKey(a.getCommonId())){

                        Store store = storeMap.get(a.getCommonId());
                        a.setStoreName(store.getName());
                        a.setLogoUrl(AppConfigUtil.getUrlPrefix(store.getLogo(), EFileSize.logo.getValue()));
                    }
                }
            }
        }

        return adPageVoIPage;
    }

    /**
     * 用户查询广告
     */
    @Override
    public List<UserAdVo> listAd() {
        LambdaQueryWrapper<Ad> wrapper = Wrappers.lambdaQuery();
        wrapper.select(Ad::getCover,Ad::getUrl,Ad::getCommonId,Ad::getType)
                .eq(Ad::getStatus,EStatus.on.getValue())
                .and(i -> i.lt(Ad::getStartTime,TimeUtil.unixTime()).gt(Ad::getEndTime,TimeUtil.unixTime()));

        List<Ad> ads = baseMapper.selectList(wrapper);
        if (CollectionUtil.isNotEmpty(ads)) {
            List<UserAdVo> adVoList = new ArrayList<>();
            for (Ad a : ads) {
                UserAdVo adVo = BeanUtil.copyProperties(a, UserAdVo.class);
                adVo.setCover(AppConfigUtil.getUrlPrefix(adVo.getCover()));
                adVo.setUrl(AppConfigUtil.getUrlPrefix(adVo.getUrl()));
                adVoList.add(adVo);
            }
            return adVoList;
        }

        return Collections.emptyList();
    }


    @Override
    public String getCover(Integer id) {

        LambdaQueryWrapper<Ad> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(Ad::getCover).eq(Ad::getId,id);
        Ad ad = getOnly(queryWrapper);

        return ObjectUtil.isEmpty(ad) ? "" : ad.getCover();
    }
}